//https://blog.csdn.net/LLL_liuhui/article/details/80361928
var _columns = [
    {checkbox: true, colspan: 1, rowspan: 1},
    {title: '序号', field: 'id', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {
        title: '序号', field: 'showId', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true,
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    {title: '企业类型', field: 'companyType', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {title: '产品名称', field: 'productName', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {title: '限值(hiden)', field: 'limit', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {title: '限值', field: 'baseline', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {title: '单位', field: 'unit', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},

    {title: '污染物排放监控位置', field: 'position', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
    {title: '备注', field: 'note', align: 'center', valign: 'middle', colspan: 1, rowspan: 1, sortable: true},
]


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#data_table').bootstrapTable({
            url: '/meta_baseline/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: false,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            sortable: true,                     //是否启用排序
            sortOrder: "desc",                  //排序方式
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            //label_id: meta_standard_id,
            stNumber: meta_standard_number,
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
            // 跳过 checkbox 和 id
            $('#new_company_type').val('');
            $("#newProduct_Name").val('');
            $("#newLimit").val('');
            $("#newBaseline").val('');
            $("#newPosition").val('');
            $("#newnote").val('');

            $('#new_data').modal();
        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            } else if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            $('#edit_data_body').empty();
            //量产为模态框赋值
            $('#edit_company_type').val(arrselections[0]['companyType'])
            $('#editProduct_Name').val(arrselections[0]['productName']);
            $('#editLimit').val(arrselections[0]['limit']);
            $('#editBaseline').val(arrselections[0]['baseline']);
            $('#editUnite').val(arrselections[0]['unit']);
            $('#editPosition').val(arrselections[0]['position']);
            $('#editnote').val(arrselections[0]['note']);

            $('#edit_data').modal();
        });


        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#data_table").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            values = [];
            for (var i = 0; i < arrselections.length; i++)
                values.push(arrselections[i].id);

            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/meta_baseline/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                if (data['status'] == "success") {
                                    bootoast({
                                        message: '删除成功',
                                        position: 'top',
                                        type: 'success',
                                        timeout: 1.5,
                                    });
                                    $("#data_table").bootstrapTable('refresh');
                                } else {
                                    bootoast({
                                        message: '删除失败\n' + data['msg'],
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            }
                        });
                    }
                }
            })

        });


        //新增框内的提交
        $('#new_data_submit').on('click', function () {

            var companyType = $('#new_company_type').val()
            var productName = $('#newProduct_Name').val()
            var limit = $('#newLimit').val()
            var baseline = $('#newBaseline').val()
            var unit = $('#newUnite').val()
            var position = $('#newPosition').val()
            var note = $('#newnote').val()

            alert(companyType)

            if (companyType == "" || companyType == null) {
                bootoast({
                    message: '请选择企业类型',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            if (productName == "" || productName == null) {
                bootoast({
                    message: '请输入产品名称',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            if (baseline == "" || baseline == null) {
                bootoast({
                    message: '请输入限值',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }


            $.ajax({
                type: "post",
                url: "/meta_baseline/insert",
                data: {
                    'companyType': companyType,
                    'productName': productName,
                    'limit': limit,
                    'baseline': baseline,
                    'unit': unit,
                    'position': position,
                    'note': note,
                    'stNumber': meta_standard_number,
                },
                success: function (data) {
                    if (data['status'] == "success") {
                        bootoast({
                            message: '插入成功',
                            position: 'top',
                            type: 'success',
                            timeout: 2,
                        });
                        $("#new_data").modal('hide');
                        $("#data_table").bootstrapTable('refresh');
                    } else {
                        bootoast({
                            message: '插入失败\n' + data['msg'],
                            position: 'top',
                            type: 'danger',
                            timeout: 2,
                        });
                    }
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        //编辑框内的提交
        $('#edit_data_submit').click(function () {
            var id = $("#data_table").bootstrapTable('getSelections')[0]['id'];
            var companyType = $('#edit_company_type').val()
            var productName = $('#editProduct_Name').val()
            var limit = $('#editLimit').val()
            var baseline = $('#editBaseline').val()
            var unit = $('#editUnite').val()
            var position = $('#editPosition').val()
            var note = $('#editnote').val()

            if (1) {
                // alert("确定");
                $.ajax({
                    type: "post",
                    url: "/meta_baseline/update",
                    data: {
                        'id': id,
                        'companyType': companyType,
                        'productName': productName,
                        'limit': limit,
                        'baseline': baseline,
                        'unit': unit,
                        'position': position,
                        'note': note,
                        'stNumber': meta_standard_number,

                    },
                    success: function (data) {
                        if (data['status'] == "success") {
                            bootoast({
                                message: '修改成功',
                                position: 'top',
                                type: 'success',
                                timeout: 2,
                            });
                            $("#edit_data").modal('hide');
                            $("#data_table").bootstrapTable('refresh');
                        } else {
                            bootoast({
                                message: '修改失败\n' + data['msg'],
                                position: 'top',
                                type: 'danger',
                                timeout: 2,
                            });
                        }
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            } else {
                // alert("取消");
                $("#edit_data").modal('hide');
                return false;
            }
        });
        //搜索按钮
        $('#btn_search').click(function () {
            $('#search_content').val("");
            $('#search_data').modal();
        });

        $('#search_data_submit').click(function () {
            var ids = [];
            var searchContent = $('#search_content').val();
            var data = $('#data_table').bootstrapTable('getData', false);//获取所有数据
            for (var i = 0; i < data.length; i++) {
                var flag = false;
                for (var prop in data[i]) {
                    if (prop == 'companyType' || prop == 'productName' || prop == 'baseline' || prop == 'unit' || prop == 'position' || prop == 'note') {
                        if (String(data[i][prop]).indexOf(String(searchContent)) != -1) {
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag) {
                    ids.push(parseInt(data[i]['id']));
                }
            }
            $('#data_table').bootstrapTable('remove', {'field': 'id', 'values': ids});
            $('#search_data').modal('hide');
        });
    };
    return oInit;
};

$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
    //添加表尾
    //add_table_foot();

    $('#data_table').bootstrapTable('hideColumn', 'id');
    $('#data_table').bootstrapTable('hideColumn', 'limit');

});


//返回上级页面
$("#btn_return").click(function () {
    $('#page-wrapper').load('pages/meta_discharge.html');
});



